import 'dart:async';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:star_author/api/common_page_load_list_api.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/event_bus/open_live_current_good_event.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/views/products/bidding_product_list_item.dart';
import 'package:star_author/widgets/button_widget.dart';
import 'package:star_author/widgets/custom_list/common_page_load_controller.dart';
import 'package:star_author/widgets/custom_list/custom_loading_more_list.dart';
import 'package:star_author/widgets/custom_list/pull_to_refresh_header.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';

import '../../../event_bus/global_event_bus.dart';
import '../../../event_bus/live_current_good_event.dart';
import '../../../generated/json/base/json_convert_content.dart';
import '../../../utils/media_recorder_util.dart';
import '../../../utils/utils.dart';
import '../../../widgets/dialog/get_dialog.dart';
import '../../../widgets/image_widget.dart';
import '../../../widgets/qr_code_widget.dart';
import '../../products/bidder_goods_detail_page/bidder_goods_detaill_page.dart';
import '../BarrageWidget.dart';
import '../model/live_good_list_entity.dart';
import 'delete_word_dialog.dart';
import 'last_backflow_good_info.dart';
import 'select_evaluate_dialog.dart';

enum ExplainType { first, lines, last, recording }

//todo:货品清单
class GoodList extends StatefulWidget {
  LiveFrom liveFrom;

  int totalCount;

  late RtcEngine? engine;
  int id;

  Map studioDetail;

  Function? muteCallBack;

  GoodList({
    Key? key,
    this.liveFrom: LiveFrom.User,
    required this.totalCount,
    this.studioDetail: const {},
    this.engine,
    this.muteCallBack,
    this.id: 0,
  }) : super(key: key);

  @override
  _GoodListState createState() => _GoodListState();
}

class _GoodListState extends State<GoodList> {
  late StreamSubscription<LiveCurrentGoodEvent>
      _currentGoodStreamSubscriptionstream;

  List<LiveGoodListData> first = [];

  bool loading = false;

  get isUser {
    return widget.liveFrom == LiveFrom.User;
  }

  late List tabs = [
    {
      'label': "待讲解",
      'keyName': 'recording',
      'condition': {
        "with_recording_video": 'false',
        "requested": 'false',
        "explaining": 'false',
        "sorts": "first_request_time_asc_and_timeout_top",
      }
    },
    {
      'label': '已讲解',
      'keyName': 'recording',
      'condition': {
        "with_recording_video": 'true',
      }
    },
  ];

  int searchResultCount = 0;

  bool isSearch = false; //是否搜索状态

  int _activeIndex = 0;

  double size = 112.w;

  double width = 68;

  double height = 38;
  double button_height = 32;

  late CommonPageLoadController loadController;
  late CommonPageLoadListApi loadListApi;

  //讲解队列
  int backflows_with_requersting_count = 0;

  //看讲解
  int backflows_with_recording_video_count = 0;

  //待讲解
  int backflows_with_to_recording_video_count = 0;

  //求讲解
  int backflows_without_recording_video_and_request_count = 0;

  @override
  void initState() {
    super.initState();
    if (widget.liveFrom == LiveFrom.Anchor) {
      width = 80;
    } else {
      width = 68;
    }
    getFirstGood();

    loadListApi = CommonPageLoadListApi(
        context, '/api/v1/studios/${StreamConf.liveId}/backflows');
    getRequestParam();
    loadController = CommonPageLoadController(
      loadListApi,
      (json) => json,
      returnListLength: (data) {
        int count = data['meta']?['total_count'] ?? 0;
        setToVideoRecoding(count);
      },
    );
    getSummaryOfBackFlows();

    _currentGoodStreamSubscriptionstream =
        GlobalEventBus().bus.on<LiveCurrentGoodEvent>().listen((event) {
      first = event.dataList;
      update(() {});
    });
  }

  //讲解中
  void getFirstGood({String q: ""}) async {
    Map<String, dynamic>? map = {
      "explaining": true,
    };
    if (q.isNotEmpty) {
      map['q'] = q;
    }
    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/backflows',
      isLoading: false,
      isErrorToast: false,
      queryParameters: map,
    ).then((value) {
      LiveGoodListEntity? entity =
          JsonConvert.fromJsonAsT<LiveGoodListEntity>(value.data);
      first = entity?.data ?? [];
      update(() {});
    });
  }

  getTotal() async {
    await HttpUtil.commonRequest(
            Get.context!, '/api/v1/studios/${StreamConf.liveId}/backflows',
            isLoading: false, isErrorToast: false)
        .then((value) {
      LiveGoodListEntity? listEntity =
          JsonConvert.fromJsonAsT<LiveGoodListEntity>(value.data);
      widget.totalCount = listEntity?.meta?.totalCount ?? 0;
      update(() {});
    });
  }

  void getRequestParam() {
    Map<String, dynamic> _tempMap = {};
    if (_activeIndex >= 0) {
      _tempMap = tabs[_activeIndex]['condition'] ?? {};
    }
    if (controller.text.isNotEmpty) {
      _tempMap['q'] = controller.text;
    } else {
      _tempMap.remove('q');
    }
    loadListApi.requestParams = _tempMap;
  }

  void getSummaryOfBackFlows() {
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${StreamConf.liveId}/summary_of_backflows',
      queryParameters: {
        'q': controller.text,
      },
      isErrorToast: false,
      isLoading: false,
    ).then((value) {
      widget.totalCount = value.data['total_count'] ?? 0;
      backflows_with_requersting_count =
          value.data['backflows_with_requersting_count'] ?? 0;
      backflows_with_recording_video_count =
          value.data['backflows_with_recording_video_count'] ?? 0;
      backflows_without_recording_video_and_request_count =
          value.data['backflows_without_recording_video_and_request_count'] ??
              0;
      setTabsLabelText();
    });
  }

  setToVideoRecoding(count) {
    LogUtil.v("loadListApi.requestParams:${loadListApi.requestParams}");
    if ((loadListApi.requestParams['with_recording_video'] ?? "") == 'false') {
      int index_where = tabs.indexWhere((element) =>
          (element["condition"]['with_recording_video']) == 'false');
      backflows_with_to_recording_video_count = count;
      tabs[index_where]['label'] =
          "待讲解($backflows_with_to_recording_video_count)";
      LogUtil.v("tabs[index_where]['label']:${tabs[index_where]['label']}");
      setState(() {});
    }
  }

  //刷新列表
  void onRefreshPage({bool isAll = false}) async {
    getFirstGood();
    if (isAll) {
      getRequestParam();
      loadController.refresh();
      getSummaryOfBackFlows();
    } else {
      getControllerTotalAndRefresh();
    }
  }

  void getControllerTotalAndRefresh() async {
    getRequestParam();
    await loadController.refresh();
    getSummaryOfBackFlows();
  }

  checkPrice(Function nextCall) {
    if (first.length > 0) {
      if (!(first[0].show_price_options ?? false)) {
        nextCall();
      } else {
        if (StreamConf.currentGoodSeconds <=
            MediaRecorderUtil.shortestRecordingVideoTime) {
          nextCall();
        } else {
          //主播已经估价
          if ((first[0].priceRange?.length ?? 0) == 0) {
            Get.bottomSheet(
              SelectEvaluateDialog(
                searchText: "",
                studioDetail: widget.studioDetail,
                engine: widget.engine,
                data: first[0],
                muteCallBack: widget.muteCallBack,
                select_reference: {},
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(16.w),
                ),
              ),
              barrierColor: Colors.transparent,
              isScrollControlled: true,
            );
            return;
          } else {
            nextCall();
          }
        }
      }
    } else {
      nextCall();
    }
  }

  void setTabsLabelText() {
    tabs.forEach((element) {
      if (element["keyName"] == "requesting") {
        element['label'] = "讲解队列" + "($backflows_with_requersting_count)";
      } else if (element["keyName"] == "recording") {
        String label = isUser ? '看讲解' : "已讲解";
        if ((element["condition"]['with_recording_video']) == 'false') {
          label = "待讲解";
          element['label'] = "$label($backflows_with_to_recording_video_count)";
        } else {
          element['label'] = "$label($backflows_with_recording_video_count)";
        }
      } else if (element["keyName"] == "recording_and_request") {
        String label = isUser ? '求讲解' : '待讲解';
        element['label'] =
            "$label($backflows_without_recording_video_and_request_count)";
      }
    });
    update(() {});
  }

  void onSearch() async {
    searchResultCount = 0;
    getRequestParam();
    await loadController.refresh();
    searchResultCount = loadController.totalCount;
    setState(() {});
  }

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      width: Get.width,
      constraints: BoxConstraints(
        maxHeight: Get.height * 0.85,
      ),
      padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
      child: Column(
        children: [
          buildTitleWidget(),
          if (controller.text.isNotEmpty)
            Container(
              alignment: Alignment.centerLeft,
              margin: EdgeInsets.only(top: 6.w, left: 12.w, bottom: 10.w),
              child: Text(
                '共$searchResultCount个搜索结果',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: UIConstant.color33,
                ),
              ),
            ),
          buildExplainFirstWidget(),
          if (controller.text.isEmpty) buildMenu(),
          Expanded(
            flex: 1,
            child: Container(
              child: PullToRefreshNotification(
                onRefresh: () async {
                  onRefreshPage(isAll: controller.text.isEmpty);
                  return true;
                },
                maxDragOffset: 80.w,
                child: CustomScrollView(
                  slivers: [
                    SliverToBoxAdapter(
                      child: PullToRefreshContainer((info) {
                        return PullToRefreshHeader(info);
                      }),
                    ),
                    CustomLoadingMoreList(
                      (ctx, item, index) {
                        ExplainType type = ExplainType.first;
                        if (_activeIndex <= 0) {
                          type = ExplainType.lines;
                        } else if (_activeIndex == 1) {
                          type = ExplainType.recording;
                        } else if (_activeIndex == 2) {
                          type = ExplainType.last;
                        }
                        if (item == null) {
                          return Container();
                        }
                        return buildGood(
                          LiveGoodListData.fromJson(
                              item as Map<String, dynamic>),
                          type,
                          index: index,
                        );
                      },
                      loadController,
                      isSliver: true,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildGood(LiveGoodListData data, ExplainType explainType, {int index: 0}) {
    return buildAnchorGood(
      data,
      explainType,
      index: index,
    );
  }

  buildMenu() {
    return Container(
      height: 50.w,
      padding: EdgeInsets.only(
        left: 12.w,
        right: 12.w,
      ),
      alignment: Alignment.centerLeft,
      child: Row(
        mainAxisAlignment:
            isUser ? MainAxisAlignment.start : MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: List.generate(tabs.length, (index) {
          return GestureDetector(
            onTap: () {
              update(() {
                _activeIndex = index;
              });

              getControllerTotalAndRefresh();
            },
            behavior: HitTestBehavior.opaque,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: (ScreenUtil().screenWidth - 24.w) / 3.2,
                  alignment: Alignment.center,
                  child: Text(
                    tabs[index]['label'],
                    style: TextStyle(
                      color: UIConstant.color33,
                      fontSize: _activeIndex == index ? 14.sp : 12.sp,
                      fontWeight: _activeIndex == index
                          ? FontWeight.w500
                          : FontWeight.w400,
                    ),
                  ),
                ),
                Opacity(
                  opacity: _activeIndex == index ? 1 : 0,
                  child: Container(
                    margin: EdgeInsets.only(top: 4.w),
                    width: 20.w,
                    height: 3.w,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Color(0xff44A949),
                          Color(0xffB2CF87),
                        ],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                      ),
                      borderRadius: BorderRadius.all(
                        Radius.circular(50),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        }),
      ),
      color: Colors.white,
    );
  }

  //求讲解和主播
  buildExplainLastTitleWidget() {
    String title = "";
    if (isUser) {
      title = "如需讲解请点击“求讲解”按钮将货品加入讲解列队等待讲解";
    } else {
      title = "以下货品暂未加入讲解列队";
    }
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(
        top: 10.w,
        left: 12.w,
      ),
      child: Text(
        title,
        style: TextStyle(
          fontSize: 12.sp,
          color: UIConstant.color99,
        ),
      ),
    );
  }

  //讲解中
  buildExplainFirstWidget() {
    if (first.length == 0) {
      return Container();
    }
    return buildGood(first[0], ExplainType.first);
  }

  bool isShowAll = false; //是否显示全部

  bool isShowRecordingAll = false; //是否显示录制全部

  TextEditingController controller = TextEditingController();

  buildTitleWidget() {
    return Container(
        padding: EdgeInsets.only(top: 18.w, bottom: 12.w, left: 12.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              child: Padding(
                child: Icon(
                  Icons.arrow_back_ios,
                  color: UIConstant.color33,
                  size: 18.sp,
                ),
                padding: EdgeInsets.only(
                    right: 12.w, top: 5.w, left: 6.w, bottom: 5.w),
              ),
              onTap: () async {
                Get.back();
              },
            ),
            Expanded(
              child: Container(
                height: height.w,
                margin: EdgeInsets.only(
                  right: 12.w,
                ),
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                  color: Color(0xFFF5F5F5),
                  borderRadius: BorderRadius.all(Radius.circular(50)),
                ),
                child: TextFormField(
                  onFieldSubmitted: (String keyword) {
                    this.controller.text = keyword;
                    _activeIndex = -1;
                    if (keyword.isEmpty) {
                      onRefreshPage();
                    } else {
                      onSearch();
                    }
                  },
                  onChanged: (val) {},
                  controller: controller,
                  textAlignVertical: TextAlignVertical.center,
                  style: TextStyle(
                    fontSize: 14.0.sp,
                    color: ColorConf.gray,
                  ),
                  decoration: InputDecoration(
                    hintText: '搜索货品编码/标题关键字',
                    hintStyle:
                        TextStyle(fontSize: 14.sp, color: ColorConf.lightGray),
                    prefixIcon: Padding(
                      padding: EdgeInsets.only(left: 12.w, right: 10.w),
                      child: RoucesUtil.getAssetsIcon('home/search', 16),
                    ),
                    prefixIconConstraints: BoxConstraints(
                      minWidth: 30,
                      minHeight: height.w,
                    ),
                    suffixIcon: buildSuffixIcon(),
                    suffixIconConstraints: BoxConstraints(
                      minWidth: 30,
                      minHeight: height.w,
                    ),
                    contentPadding: EdgeInsets.zero,
                    isCollapsed: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.all(Radius.circular(50)),
                    ),
                    isDense: true,
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  Widget? buildSuffixIcon() {
    if (controller.text.isNotEmpty) {
      return GestureDetector(
        child: Icon(
          Icons.cancel,
          color: ColorConf.lightGray,
          size: 20.w,
        ),
        onTap: () {
          FocusScope.of(context).unfocus();
          controller.clear();
          _activeIndex = 0;
          onRefreshPage();
        },
      );
    } else {
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          QRCodeUtil.show(context, entrance: QRCodeDialog.stream,
              callback: (val) {
            //搜索
            this.controller.text = val;

            if (val.isEmpty) {
              _activeIndex = 0;
              onRefreshPage();
            } else {
              _activeIndex = -1;
              onSearch();
            }
          });
        },
        child: Padding(
          padding:
              EdgeInsets.only(right: 8.w, top: 5.w, bottom: 5.w, left: 20.w),
          child: RoucesUtil.getAssetsIcon('ic_scan_lt', 16.w),
        ),
      );
    }
  }

  setSEI(LiveGoodListData data) {
    //SEI打点数据
    // Map map = {
    //   'live_key': StreamConf.channelKey,
    //   'anchor_name': widget.studioDetail['living_anchor']['nickname'] ?? "",
    //   'serial': data.goods?.serial ?? "",
    //   'title': data.goods?.title ?? "",
    //   'category': data.goods?.category ?? "",
    //   'backflow_id': data.id,
    //   'time': DateUtil.getNowDateStr(),
    // };
    // widget.engine?.updateRtmpTranscoding(
    //   LiveTranscoding(
    //     StreamConf.users,
    //     userConfigExtraInfo: json.encode(map),
    //   ),
    // );
  }

  buildTopLinesText(LiveGoodListData data) {
    if ((data.evaluatedTimeHour ?? 0) > 0) {
      return Container(
        margin: EdgeInsets.only(
          top: 10.w,
        ),
        child: Text.rich(
          TextSpan(
            text: '已上架',
            children: [
              TextSpan(
                text: (data.evaluatedTimeHour ?? 0).toString(),
                style: TextStyle(
                  color: rgba(224, 32, 32, 1),
                ),
              ),
              TextSpan(
                text: '小时',
              ),
            ],
          ),
          style: TextStyle(
            fontSize: 12.sp,
            color: rgba(153, 153, 153, 1),
          ),
        ),
      );
    }
    return Container();
  }

  buildLivingWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset(
          'images/video_loading_lt.gif',
          width: 10.w,
          height: 12.w,
          color: Color(0xFFF04529),
        ),
        SizedBox(
          width: 6.w,
        ),
        Text(
          "讲解中",
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.white,
          ),
        )
      ],
    );
  }

  buildCover(data) {
    return ClipRRect(
      child: ImageWithPlaceHolder(
        width: 90.w,
        height: 90.w,
        cover: data.goods?.cover?.url ?? "",
        radius: 4,
      ),
      borderRadius: BorderRadius.circular(
        4.w,
      ),
    );
  }

  //主播布局
  buildAnchorGood(LiveGoodListData data, ExplainType explainType,
      {int index: 0}) {
    bool isExplain = explainType == ExplainType.first;
    buildButtons() {
      if (data.recordingVideo?.isNotEmpty ?? false) {
        return ButtonWidget(
          child: Text(
            "删除录播",
            style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: UIConstant.color33),
          ),
          type: ButtonType.bdGrayWithTextBlack,
          width: width,
          height: button_height,
          onPressed: () {
            showGetDialog(DeleteRecordingDialog(
              delete: () async {
                HttpUtil.commonRequest(Get.context!,
                    '/api/v1/backflows/${data.id}/detach_recording_video',
                    method: HttpUtil.MethodPut,
                    data: {
                      "anchor_id": MediaRecorderUtil.anchorId,
                    }).then((value) {
                  loadController.removeAt(index);
                  backflows_with_recording_video_count -= 1;
                  backflows_without_recording_video_and_request_count += 1;
                  setTabsLabelText();
                });
              },
            ));
          },
        );
      }
      if (data.explainerId != null) {
        //已经讲解
        return ButtonWidget(
          child: Text(
            "结束讲解",
            style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: UIConstant.color33),
          ),
          type: ButtonType.bdGrayWithTextBlack,
          width: width,
          height: button_height,
          onPressed: () {
            checkPrice(() {
              MediaRecorderUtil.stopRecording();
              //SEI打点数据
              setSEI(data);
              HttpUtil.commonRequest(Get.context!,
                      '/api/v1/studios/${StreamConf.liveId}/stop_explaining',
                      queryParameters: {
                        "backflow_id": data.id,
                      },
                      method: HttpUtil.MethodPut)
                  .then((value) {
                if (value.statusCode == 200) {
                  RongUtil.operation(OperationKey.start_explain, {});
                  GlobalEventBus().bus.fire(OpenLiveCurrentGoodEvent(null));
                  CustomToast.show("已结束讲解，当前无讲解");
                  onRefreshPage();
                }
              });
            });
          },
        );
      }
      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          ButtonWidget(
            child: Text(
              "开始讲解",
              style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: Colors.white),
            ),
            type: ButtonType.bgOrange,
            width: width,
            height: button_height,
            onPressed: () {
              checkPrice(() {
                List<Map> list =
                    SpUtil.getObjectList(MediaRecorderUtil.localKey) ?? [];
                int index = list.indexWhere((element) =>
                    element['id'].toString() == data.id.toString());
                if (index == -1) {
                  list.add({
                    ...data.toJson(),
                    "anchorId": MediaRecorderUtil.anchorId,
                    "liveName": widget.studioDetail['name'] ?? "",
                    "anchorName":
                        widget.studioDetail['living_anchor']['nickname'] ?? "",
                    "isAgree": true,
                  });
                }
                MediaRecorderUtil.stopRecording();
                //SEI打点数据
                setSEI(data);
                SpUtil.putObjectList(MediaRecorderUtil.localKey, list);
                HttpUtil.commonRequest(Get.context!,
                        '/api/v1/studios/${StreamConf.liveId}/start_explaining',
                        queryParameters: {
                          "backflow_id": data.id,
                        },
                        method: HttpUtil.MethodPut)
                    .then((value) {
                  if (value.statusCode == 200) {
                    //当我们服务器请求成功才开始录制 不然网络不好的时候会多录制一些脏数据
                    widget.engine?.muteLocalAudioStream(false);
                    if (widget.muteCallBack != null) {
                      widget.muteCallBack!();
                    }
                    MediaRecorderUtil.startRecording(data.id ?? 0);
                    CustomToast.show("已切换所讲解的货品");
                    data.start_explaining = false;
                    GlobalEventBus().bus.fire(OpenLiveCurrentGoodEvent(data));
                    RongUtil.operation(OperationKey.start_explain, {});
                    onRefreshPage();
                  }
                });
              });
            },
          ),
        ],
      );
    }

    bool isShow = data.isExplained ?? false;
    buildLeftWidget() {
      //是否转回流 转回流显示转回流
      if (data.last_history_backflow != null) {
        return BackflowGoodWidget(
          param: data.last_history_backflow,
        );
      }
      return Container();
    }

    bool showBg = false;

    if ((explainType == ExplainType.lines) && (data.isRequested ?? false)) {
      showBg = true;
    }

    Widget child = Container(
      height: size,
      color: showBg ? Color(0xfff7fbf0) : Colors.white,
      child: Row(
        children: [
          GestureDetector(
            child: Container(
              width: 90.w,
              height: 90.w,
              child: Stack(
                clipBehavior: Clip.antiAlias,
                children: [
                  buildCover(data),
                  if (isShow)
                    Positioned(
                        child: RoucesUtil.getAssetsIcon(
                            'ic_live_good_triangle_lt', 20.w)),
                  if (explainType == ExplainType.first)
                    Positioned(
                      child: Container(
                        height: 20.w,
                        decoration: BoxDecoration(
                          color: rgba(0, 0, 0, 0.50),
                          borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(4.w),
                            bottomRight: Radius.circular(4.w),
                          ),
                        ),
                        alignment: Alignment.center,
                        child: buildLivingWidget(),
                        width: 90.w,
                      ),
                      bottom: 0,
                      left: 0,
                    ),
                ],
              ),
            ),
            onTap: () {
              toDetailPage(data, false);
            },
          ),
          SizedBox(
            width: 10.w,
          ),
          Expanded(
            child: Container(
              height: 90.w,
              child: Stack(
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          GestureDetector(
                            child: Text.rich(
                              TextSpan(
                                children: [
                                  WidgetSpan(
                                    child: Baseline(
                                      baseline: 14.w,
                                      baselineType: TextBaseline.alphabetic,
                                      child: Container(
                                        margin: EdgeInsets.only(
                                          right: 6.w,
                                        ),
                                        child: Image(
                                          image: AssetImage(
                                              'images/lt_user/owner/level_${data.user_normal_level}.png'),
                                          width: 26.w,
                                          height: 14.w,
                                          fit: BoxFit.cover,
                                        ),
                                      ),
                                    ),
                                  ),
                                  TextSpan(
                                    text: data.goods?.title ?? "",
                                  ),
                                ],
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: ColorConf.normal,
                                  fontWeight: FontWeight.w500,
                                  height: 14 / 16,
                                ),
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                            onTap: () {
                              toDetailPage(data, false);
                            },
                          ),
                          if (data.recordingVideo?.isEmpty ?? false)
                            buildTopLinesText(data),
                          if ((data.priceRange?.length ?? 0) > 0 &&
                              ![ExplainType.recording].contains(explainType))
                            Container(
                              margin: EdgeInsets.only(
                                top: 5.w,
                              ),
                              child: Text(
                                "最终估价 ${getPriceWithList(
                                  data.priceRange ?? [],
                                  intl: true,
                                )}",
                                style: TextStyle(
                                  color: rgba(224, 32, 32, 1),
                                  fontSize: 12.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                  Positioned(
                    child: Container(
                      width: Get.width - 12.w - 12.w - 90.w - 10.w,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          buildLeftWidget(),
                          buildButtons(),
                        ],
                      ),
                    ),
                    bottom: 0,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
      padding: EdgeInsets.only(bottom: 5.w, left: 12.w),
    );
    if (isExplain) {
      return Column(
        children: [
          child,
          Container(
            height: 10.w,
            color: Color(0xFFF8F8F8),
          ),
        ],
      );
    }
    return child;
  }

  toDetailPage(LiveGoodListData data, bool isNeedShowPriceDialog) {
    Get.to(
        BidderGoodsDetailPage(
          id: data.id ?? 0,
          formDetail: BiddingProductListItemFormType.Live,
          isNeedShowPriceDialog: isNeedShowPriceDialog,
        ),
        preventDuplicates: false);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _currentGoodStreamSubscriptionstream.cancel();
  }
}
